package com.kotlin.book.activity

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.kotlin.book.R
import com.kotlin.book.databinding.ActivityMainBinding
import com.kotlin.book.fragments.ClassFragment
import com.kotlin.book.fragments.HomeFragment
import com.kotlin.book.fragments.ShelfFragment

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private val homeFragment = HomeFragment()
    private val classFragment = ClassFragment()
    private val shelfFragment = ShelfFragment()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        //根据系统ui设置边距
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }


        val bottomNavigationView = binding.bottomNavigation

        // 初始化默认选中的 Fragment
        val fragments = listOf(homeFragment, classFragment, shelfFragment)
        supportFragmentManager.beginTransaction().apply {
            fragments.forEach { add(binding.fragmentContainer.id, it).hide(it) }
            show(homeFragment) // 默认显示 homeFragment
        }.commit()

        // 设置点击监听器
        bottomNavigationView.setOnItemSelectedListener { item ->
            val fragmentToShow = when (item.itemId) {
                R.id.nav_home -> homeFragment
                R.id.nav_class -> classFragment
                R.id.nav_book -> shelfFragment
                else -> null
            }

            // 如果选择的 Fragment 不为空，进行显示和隐藏操作
            fragmentToShow?.let {
                supportFragmentManager.beginTransaction().apply {
                    fragments.forEach { hide(it) } // 隐藏所有 Fragment
                    show(it) // 显示当前选择的 Fragment
                }.commit()
            }

            true
        }
    }
}